<template>
    <div class="essay_edit">

        <div class="edit">
            <div style="text-align: center;width: 100%;font-size: 1.5vw;margin: 0.5vw 0;">编辑</div>
            <el-form :model="forms" ref="formRef" :rules="rules" label-width="180px" :inline="false" size="normal">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="forms.title"></el-input>
                </el-form-item>
                <el-form-item label="分类" size="normal">
                    <el-radio-group v-model="forms.Essay_type" @change="choice">
                        <el-radio border value="0">博客</el-radio>
                        <el-radio border value="1">日常</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label="'封面'">
                    <el-upload class="avatar-uploader" :action="base_url + '/essay/upload'" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="forms.cover_img" :src="base_url + forms.cover_img" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="标签" size="normal" prop="tags">
                    <el-select v-model="forms.tags" multiple placeholder="选择" style="width: 240px" @change="change">
                        <el-option v-for="item in opt" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="文本" size="normal">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                        :mode="mode" />
                    <Editor style="height: 350px;width: 100%; overflow-y: hidden;" v-model="valueHtml"
                        :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit(formRef)">立即创建</el-button>
                    <el-button @click="router.back()">取消</el-button>
                </el-form-item>
            </el-form>

        </div>
    </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, reactive, shallowRef, onMounted } from 'vue'
//@ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Plus } from '@element-plus/icons-vue'
import { IToolbarConfig } from '@wangeditor/editor'
import axios from 'axios'
import { ElMessage, type FormInstance } from 'element-plus'
import { type Eassay } from "@/types/Eassy"
import EssayStore from '@/store/EssayStore'
import { useRouter } from 'vue-router'
const router = useRouter()
const store = EssayStore()
const base_url = import.meta.env.VITE_APP_URL
const formRef = ref<FormInstance>()
const forms = reactive<Eassay>({
    title: "",
    rich_text: "",
    textual: "",
    Essay_type: '0',
    cover_img: "",
    tags: [],
    publish_time: Date.now(),
    end_time: Date.now()
})

//表单校验---start------
//自定义校验规则----start---

const validateTags = (rules: any, value: any, callback: any) => {
    if (value.length < 1) {
        callback(new Error('至少一个标签'))
    } else {

        callback()
    }
}
//自定义校验规则----end----
const rules = reactive({
    title: [
        { required: true, message: '必填字段', trigger: 'blur' },
        { min: 3, message: '至少5个字符', trigger: 'blur' },
    ],

    tags: [
        {
            type: 'array',
            required: true,
            validator: validateTags,
            trigger: 'change'
        },
    ],

})
//表单校验---end---------
const opt = ref([
    {
        value: '前端',
        label: '前端',
    },
    {
        value: 'nodejs',
        label: 'nodejs',
    },
    {
        value: 'web',
        label: 'web',
    },
    {
        value: 'java',
        label: 'java',
    },
    {
        value: 'mongodb',
        label: 'mongodb',
    },
    {
        value: 'mysql',
        label: 'mysql',
    },
    {
        value: 'c++',
        label: 'c++',
    },
    {
        value: 'python',
        label: 'python',
    },
    {
        value: 'vue',
        label: 'vue',
    },
    {
        value: 'react',
        label: 'react',
    },
])
const options = [
    {
        value: '前端',
        label: '前端',
    },
    {
        value: 'nodejs',
        label: 'nodejs',
    },
    {
        value: 'web',
        label: 'web',
    },
    {
        value: 'java',
        label: 'java',
    },
    {
        value: 'mongodb',
        label: 'mongodb',
    },
    {
        value: 'mysql',
        label: 'mysql',
    },
    {
        value: 'c++',
        label: 'c++',
    },
    {
        value: 'python',
        label: 'python',
    },
    {
        value: 'vue',
        label: 'vue',
    },
    {
        value: 'react',
        label: 'react',
    },
]
const options2 = [
    {
        value: "美食",
        label: "美食",

    },
    {
        value: "出行",
        label: "出行",

    }, {
        value: "摄影",
        label: "摄影"
    }, {
        value: "回家",
        label: "回家"
    },
    {
        value: '学校',
        label: "学校"
    }, {
        value: "居家",
        label: "居家"
    },
    {
        value: "游戏",
        label: "游戏"
    },
    {
        value: '工作',
        label: "工作"
    },
    {
        value: '运动',
        label: '运动'
    }, {
        value: "番剧",
        label: "番剧"
    }
]
//改变
const change = (e: any) => {
    console.log(e)
}
//分类
const choice = (e: any) => {
    if (e == 0) {
        console.log("博客")
        opt.value = options
    } else {
        opt.value = options2
    }
    console.log(e)
}
//----上传图片---start-----------
const handleAvatarSuccess = (e: any) => {

    forms.cover_img = e.data.url


}
const beforeAvatarUpload = () => {

}
//-----------上传图片--end------------
//---------------富文本编辑区------start--------
const editorRef = shallowRef()
const mode = ref("default")
// 内容 HTML
const valueHtml = ref('<p>hello</p>')
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    }, 1500)
})

const toolbarConfig: Partial<IToolbarConfig> = {
    // const toolbarConfig = {                        
    /* 工具栏配置 */
}
const editorConfig = {
    placeholder: '请输入内容...', MENU_CONF: {
        'codeSelectLang': {

        },
        "uploadImage": {}
    }
}
editorConfig.MENU_CONF['codeSelectLang'] = {
    // 代码语言
    codeLangs: [
        { text: 'CSS', value: 'css' },
        { text: 'HTML', value: 'html' },
        { text: 'XML', value: 'xml' },
        // 其他
    ]
}
toolbarConfig.excludeKeys = [
    // 排除菜单组，写菜单组 key 的值即可
    'group-video'
]
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {

    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
//------------富文本插入图片----start------------------
editorConfig.MENU_CONF['uploadImage'] = {
    timeout: 5 * 1000,
    //默认
    fieldName: 'wangeditor-uploaded-image',
    //图片大小限制
    maxFileSize: 10 * 1024 * 1024, // 10M

    base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

    onBeforeUpload(files: any) {
        console.log('onBeforeUpload', files)

        return files // 返回哪些文件可以上传
        // return false 会阻止上传
    },
    async customUpload(file: any, insertFn: any) {                   // JS 语法
        /* file 即选中的文件
        */
        console.log(file)
        const newsform = new FormData()

        newsform.append("file", file)
        const result = await axios.post(`http://127.0.0.1:3000/essay/upload`, newsform, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        const url = 'http://127.0.0.1:3000/' + result.data.data.url
        // 最后插入图片
        insertFn(url)
    },
    onProgress(progress: any) {
        console.log('onProgress', progress)
    },
    onSuccess(file: any, res: any) {
        console.log('onSuccess', file, res)
    },
    onFailed(file: any, res: any) {
        alert(res.message)
        console.log('onFailed', file, res)
    },
    onError(file: any, err: any, res: any) {
        alert(err.message)
        console.error('onError', file, err, res)
    },

}
//------------富文本插入图片----end------------------
//------------------富文本编辑区---end-----------
const onSubmit = async (formEl: FormInstance | undefined) => {
    const html = editorRef.value.getHtml()
    const text = editorRef.value.getText()

    if (forms.cover_img.trim() == '') {
        ElMessage({
            type: "error",
            message: "请上传封面"
        })
        return
    }
    if (text.trim() == '') {
        ElMessage({
            type: "error",
            message: "富文本内容不能为空"
        })
        return
    }

    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {

            forms.rich_text = html
            forms.textual = text
            const temp_tags = forms.tags.map((item: any, index: number) => {
                return {
                    id: index,
                    title: item
                }
            })
            await store.add_essay({
                ...forms,
                tags: temp_tags
            })
        } else {
        }
    })

}
</script>

<style scoped lang="scss">
.essay_edit {
    width: 100%;
    display: flex;
    justify-content: center;

    .edit {
        width: 100%;
        background-color: rgba(255, 255, 255, 0.8);
        padding: 1vw;

    }

    :deep(img) {
        height: 200px;
        width: 200px;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;

        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        background-color: white;
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
}
</style>